package com.hui.controller;

import com.github.pagehelper.PageInfo;
import com.hui.entity.Menu;
import com.hui.entity.ResponseResult;
import com.hui.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 李昭辉
 * @Date: 2021/08/08/15:15
 * @Description:
 */
@RestController
@RequestMapping("/menu")
public class MenuController {
    @Autowired
    private MenuService menuService;

    // 查询菜单列表
    @RequestMapping("/findAllMenu")
    public ResponseResult findAllMenu(@RequestParam(defaultValue = "10") Integer currentPage,
                                      @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo<Menu> list = menuService.getAllMenuByPage(currentPage, pageSize);
        return new ResponseResult(true, 200, "查询成功", list);
    }

    // 根据菜单ID 查询菜单信息
    @RequestMapping("/findMenuInfoById")
    public ResponseResult findMenuInfoById(Integer id) {
        Map<String, Object> map = new HashMap<>();
        if (id == -1) {
            // 新增操作，只回显所有菜单
            List<Menu> parentMenuList = menuService.getAllMenuByTree();
            map.put("parentMenuList", parentMenuList);
        } else {
            // 修改操作，回显所有菜单
            List<Menu> parentMenuList = menuService.getAllMenuByTree();
            map.put("parentMenuList", parentMenuList);
            // 回显当前id的菜单
            Menu menuInfo = menuService.getMenuById(id);
            map.put("menuInfo", menuInfo);
        }
        return new ResponseResult(true, 200, "查询成功", map);
    }

    // 添加&修改菜单
    @RequestMapping("/saveOrUpdateMenu")
    public ResponseResult saveOrUpdateMenu(@RequestBody Menu menu) {
        if (menu.getId() == null) {
            // 新增
            menuService.saveMenu(menu);
            return new ResponseResult(true, 200, "保存成功", null);
        } else {
            // 修改
            menuService.updateMenu(menu);
            return new ResponseResult(true, 200, "修改成功", null);
        }
    }

    // 删除
    @RequestMapping("/deleteMenu")
    public ResponseResult deleteMenu(Integer id) {
        boolean flag = menuService.deleteMenu(id);
        if (flag) {
            return new ResponseResult(true, 200, "删除成功", null);
        } else {
            return new ResponseResult(false, 500, "删除失败:当前菜单有子菜单！！！", null);
        }
    }
}
